package com.leemz.design.chapter2.pattern;

import com.leemz.design.chapter2.none.Api;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 工厂通过提供静态方法，根据参数决定创建哪个对象
 */
public class Factory {

    private static Properties properties;
    static {
        InputStream is = Factory.class.getResourceAsStream("/factory.properties");
        properties = new Properties();
        try {
            properties.load(is);
        } catch (IOException e) {
            System.out.println("读取配置文件错误:" + e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Api createApi() {
        Api api = null;
        try {
            api = (Api) Class.forName(properties.getProperty("implClass")).newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return api;
    }
}
